import { HttpClient } from '@angular/common/http';
import { Component, ViewChild } from '@angular/core';
import { AgGridAngular } from 'ag-grid-angular';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'aggrid';
  @ViewChild('agGrid') agGrid: AgGridAngular;
  rowData:any = [];
  // 带排序和过滤的列定义
  columnDefs:any = null;
  defaultColDef:any = null;

  private gridApi;
  private gridColumnApi;

  constructor(private http: HttpClient){
    this.columnDefs = [
      { field: 'make', sortable: true, filter: true,checkboxSelection: true },
      { field: 'model', sortable: true, filter: true },
      { field: 'price', sortable: true, filter: true }
    ];
    this.defaultColDef = { resizable: true };
  }

  ngOnInit() {
    // this.rowData = this.http.get('https://raw.githubusercontent.com/ag-grid/ag-grid/master/grid-packages/ag-grid-docs/src/sample-data/smallRowData.json');
  }

  getSelectedRows() {
    const selectedNodes = this.agGrid.api.getSelectedNodes();
    const selectedData = selectedNodes.map(node => node.data );
    const selectedDataStringPresentation = selectedData.map(node => node.make + ' ' + node.model).join(', ');

    alert(`Selected nodes: ${selectedDataStringPresentation}`);
  }

  onGridReady(params) {
    this.gridApi = params.api;
    this.gridColumnApi = params.columnApi;

    // this.http
    //   .get('https://raw.githubusercontent.com/ag-grid/ag-grid/master/grid-packages/ag-grid-docs/src/sample-data/smallRowData.json')
    //   .subscribe((data) => {
    //     this.rowData = data;
    //   });
    this.rowData = [ { "make": "Toyota", "model": "Celica", "price": 35000 },
    { "make": "Ford", "model": "Mondeo", "price": 32000 },
    { "make": "Porsche", "model": "Boxter", "price": 72000 }]
  }

  sizeToFit() {
    this.gridApi.sizeColumnsToFit();
  }


  autoSizeAll(skipHeader) {
    var allColumnIds = [];
    this.gridColumnApi.getAllColumns().forEach(function (column) {
      allColumnIds.push(column.colId);
    });
    this.gridColumnApi.autoSizeColumns(allColumnIds, skipHeader);
  }

}
